<template>
  <el-container>
    <el-main>
      <div v-if="loading" class="loading">加载中...</div>
      <el-card v-else-if="post" class="post-detail">
        <!-- 帖子标题 -->
        <h1>{{ post.title }}</h1>
        <!-- 帖子元信息 -->
        <div class="post-meta">
          <p><strong>话题:</strong> {{ post.topic }}</p>
          <p><strong>发布时间:</strong> {{ formatDate(post.CreatedAt) }}</p>
          <p v-if="post.UpdatedAt !== post.CreatedAt">
            <strong>更新时间:</strong> {{ formatDate(post.UpdatedAt) }}
          </p>
          <p><strong>点赞数:</strong> {{ likes }}</p>
        </div>

        <!-- 帖子内容 -->
        <div class="post-content">
          {{ post.content }}
        </div>

        <!-- 点赞区域 -->
        <div class="like-section">
          <button @click="handleLike">👍 点赞 {{ likes }}</button>
        </div>

        <!-- 评论输入区域 -->
        <div class="comment-form">
          <textarea v-model="newCommentContent" placeholder="写点评论..."></textarea>
          <button @click="submitComment">提交评论</button>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <div v-if="comments.length === 0 && !loading" class="no-comments">暂无评论</div>
          <div v-for="comment in comments" :key="comment.ID" class="comment-item">
            <p><strong>用户ID:</strong> {{ comment.userID }}</p>
            <p><strong>内容:</strong> {{ comment.content }}</p>
            <p><strong>创建时间:</strong> {{ formatDate(comment.CreatedAt) }}</p>
            <p><strong>更新时间:</strong> {{ formatDate(comment.UpdatedAt) }}</p>
            <button v-if="canDeleteComment(comment)" @click="deleteComment(comment)">删除</button>
          </div>
          <!-- 加载更多评论 -->
          <button v-if="currentPage < totalPages" @click="fetchComments(currentPage + 1)">
            加载更多评论
          </button>
        </div>
      </el-card>

      <div v-else class="no-data">帖子不存在或已被删除</div>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted,watch } from 'vue'
import { useRoute } from 'vue-router'
import axios from '../axios'
import type { Post, Comment } from '../types/Article'
import { ElMessage } from 'element-plus'
import { useCommentStore } from '../store/auth'
const route = useRoute()
const commentStore = useCommentStore()
// 帖子数据
const post = ref<Post | null>(null)
const loading = ref(true)

// 点赞数
const likes = ref(0)

// 评论相关状态
const comments = ref<Comment[]>([])
const newCommentContent = ref('')
const currentPage = ref(1)
const totalPages = ref(0)

// 当前用户信息（从 Token 解析）
const currentUser = ref<{ id: number; level?: number } | null>(null)

// 格式化时间函数
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
}

// 获取帖子详情
const fetchPost = async () => {
  try {
    const response = await axios.get<Post>(`/api/posts/${route.params.id}`)
    post.value = response.data
  } catch (error) {
    console.error('获取帖子失败:', error)
  }
}

// 获取点赞数
const fetchLikes = async () => {
  try {
    const res = await axios.get(`/api/posts/${route.params.id}/like`)
    likes.value = res.data.likes
  } catch (error) {
    console.error('获取点赞数失败:', error)
  }
}

// 点赞处理
const handleLike = async () => {
  try {
    const res = await axios.put(`/api/posts/${route.params.id}/like`)
    likes.value = res.data.likes
  } catch (error) {
    console.error('点赞失败:', error)
  }
}

// 提交新评论
// 提交新评论
const submitComment = async () => {
  if (!newCommentContent.value.trim()) return

  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    return
  }

  if (!currentUser.value?.id) {
    ElMessage.error('认证信息异常，请重新登录')
    return
  }

  try {
    const res = await axios.post(
      `/api/posts/${route.params.id}/comments`,
      {
        content: newCommentContent.value,
        postID: Number(route.params.id), // 添加 postID
        userID: currentUser.value.id      // 添加 userID
      }
    )

    comments.value.unshift(res.data)
    newCommentContent.value = ''
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('提交评论失败')
  }
}

// 获取评论
const fetchComments = async (page = 1) => {
  try {
    const res = await axios.get<{ comments: Comment[]; totalPages: number }>(
      `/api/posts/${route.params.id}/comments`,
      {
        params: { page, size: 7 },
      }
    )

    let newComments: Comment[] = []

    if (Array.isArray(res.data)) {
      newComments = res.data.map((c: Comment) => ({ ...c }))
    } else if (Array.isArray(res.data.comments)) {
      newComments = res.data.comments.map((c: Comment) => ({ ...c }))
    }

    // 使用缓存
    if (page === 1) {
      comments.value = [...newComments]
      commentStore.addComments(route.params.id as string, [...newComments])
    } else {
      comments.value = [...comments.value, ...newComments]
    }

    currentPage.value = page
    totalPages.value = res.data.totalPages || Math.ceil(comments.value.length / 7)

  } catch (error) {
    console.error('获取评论失败:', error)

    // 加载失败时尝试使用本地缓存
    comments.value = commentStore.getComments(route.params.id as string)
  }
}

// 删除评论
const deleteComment = async (comment: Comment) => {
  try {
    await axios.delete(`/api/comments/${comment.ID}`)
    comments.value = comments.value.filter(c => c.ID !== comment.ID)
  } catch (error) {
    console.error('删除评论失败:', error)
  }
}
const fetchCurrentUser = async () => {
  try {
    const res = await axios.get('/api/users/me') // 假设存在该接口
    currentUser.value = {
      id: res.data.ID, // 将 ID 映射为 id
      level: res.data.level || 1,
     // username: res.data.username // 可选：保存用户名用于调试或显示
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}
// 判断是否可以删除评论
const canDeleteComment = (comment: Comment) => {
  if (!currentUser.value) return false
  const userLevel = currentUser.value?.level // 使用可选链防止 level 为 undefined
  const userId = currentUser.value.id
  return (userLevel !== undefined && userLevel >= 4) || userId === comment.userID
}
// watch(
//   () => route.params.id,
//   async (newId) => {
//     if (newId) {
//       currentPage.value = 1
//       await fetchComments(1)
//     }
//   }
// )
// // 初始化数据
onMounted(async () => {
  loading.value = true
  await fetchPost()
  await fetchLikes()
  await fetchComments(1)
  await fetchCurrentUser()

  // 回退使用 token 解析
  if (!currentUser.value) {
    const token = localStorage.getItem('token')
    if (token) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]))
        currentUser.value = {
          id: payload.id,
          level: payload.level || 1
        }
      } catch (e) {
        console.error('Token 解码失败:', e)
        ElMessage.error('登录状态异常，请重新登录')
      }
    }
  }

  loading.value = false
})
</script>

<style scoped>
.like-section {
  margin: 20px 0;
}

.comment-form textarea {
  width: 100%;
  height: 80px;
  padding: 10px;
  font-size: 14px;
  border-radius: 6px;
  border: 1px solid #ddd;
  resize: none;
  margin-bottom: 10px;
}

.comment-form button {
  margin-top: 5px;
}

.comments-list .comment-item {
  border-top: 1px solid #eee;
  padding: 15px 0;
}

.no-comments {
  text-align: center;
  color: #999;
  margin-top: 20px;
}
</style>